package de.slothsoft.commons.swing.treetable;

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.tree.DefaultTreeSelectionModel;

/**
 * This example shows how to create a simple JTreeTable component, by using a
 * JTree as a renderer (and editor) for the cells in a particular column in the
 * JTable.
 */

public class JTreeTable extends JTable {

	private static final long serialVersionUID = 1L;

	protected DefaultTreeTableCellRenderer tree;

	public JTreeTable(TreeTableModel treeTableModel) {
		// Create the tree. It will be used as a renderer and editor.
		this.tree = new DefaultTreeTableCellRenderer(treeTableModel);

		// Install a tableModel representing the visible rows in the tree.
		super.setModel(new TreeTableModelAdapter(treeTableModel, this.tree));

		// Force the JTable and JTree to share their row selection models.
		this.tree.setSelectionModel(new DefaultTreeSelectionModel() {
			private static final long serialVersionUID = 1L;

			// Extend the implementation of the constructor, as if:
			/* public this() */{
				setSelectionModel(this.listSelectionModel);
			}
		});
		// Make the tree and table row heights the same.
		this.tree.setRowHeight(getRowHeight());

		// Install the tree editor renderer and editor.
		setDefaultRenderer(TreeTableModel.class, this.tree);
		setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());

		setShowGrid(false);
		setIntercellSpacing(new Dimension(0, 0));
	}

	/*
	 * Workaround for BasicTableUI anomaly. Make sure the UI never tries to
	 * paint the editor. The UI currently uses different techniques to paint the
	 * renderers and editors and overriding setBounds() below is not the right
	 * thing to do for an editor. Returning -1 for the editing row in this case,
	 * ensures the editor is never painted.
	 */
	@Override
	public int getEditingRow() {
		return getColumnClass(this.editingColumn) == TreeTableModel.class ? -1
				: this.editingRow;
	}

	//
	// The renderer used to display the tree nodes, a JTree.
	//

	//
	// The editor used to interact with tree nodes, a JTree.
	//

	public class TreeTableCellEditor extends AbstractCellEditor implements
			TableCellEditor {

		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int r, int c) {
			return JTreeTable.this.tree;
		}
	}

}
